package com.luom.fsp.job.cycle;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.luom.fsp.model.entity.Order;
import com.luom.fsp.model.enums.OrderStatusEnum;
import com.luom.fsp.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.luom.fsp.constant.RedisConstant.ORDER_TIMEOUT_KEY;

/**
 * @author 28713
 * 定时任务取消超时订单
 */
@Slf4j
@Component
public class OrderTimeout {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private OrderService orderService;

    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void checkTimeoutOrders() {
        // 计算30分钟前的时间戳
        long deadline = System.currentTimeMillis() - 30 * 60 * 1000;
        Set<String> orderIds = stringRedisTemplate.opsForZSet()
                .rangeByScore(ORDER_TIMEOUT_KEY, 0, deadline);

        if (CollectionUtils.isEmpty(orderIds)) return;

        // 分批次处理
        List<String> idList = new ArrayList<>(orderIds);
        int batchSize = 100;
        for (int i=0; i<idList.size(); i+=batchSize) {
            List<String> batch = idList.subList(i, Math.min(i+batchSize, idList.size()));

            // 原子性更新数据库
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper
                    .in(Order::getId, batch)
                    .eq(Order::getOrderStatus, OrderStatusEnum.PENDING)
                    .set(Order::getOrderStatus, OrderStatusEnum.CANCELLED);
            boolean update = orderService.update(updateWrapper);

            // 批量删除Redis记录
            if (update) {
                stringRedisTemplate.opsForZSet().remove(
                        ORDER_TIMEOUT_KEY,
                        batch.toArray()
                );
            }
        }

        /*// 从Redis获取超时订单ID（按score范围查询）
        Set<String> orderIds = redisTemplate.opsForZSet()
                .rangeByScore(ORDER_TIMEOUT_KEY, 0, deadline);
        if (CollectionUtils.isEmpty(orderIds)) return;

        List<Order> orderList = orderService.query().in("id", orderIds).list();
        Set<Order> orderSet = orderList.stream()
                .filter(order -> order.getOrderStatus().equals(OrderStatusEnum.PENDING.getValue()))
                .collect(Collectors.toSet());
        //批量修改订单状态
        orderSet.forEach(order -> {
            order.setOrderStatus(OrderStatusEnum.CANCELLED.getValue());
        });
        orderService.updateBatchById(orderSet);

        // 移除超时订单ID
        List<Long> longList = orderSet.stream().map(Order::getId).collect(Collectors.toList());
        if (!longList.isEmpty()) {
            redisTemplate.opsForZSet().remove(ORDER_TIMEOUT_KEY, longList);
        }
        log.info("超时订单已取消：{}", longList);*/
    }
}
